﻿using LD.Common;
using LD.Host;
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using YTE.Control;
using 右下角弹窗.DiagShow;

namespace LD.BC
{
    public partial class FrmAxisMotion : FrmBase
    {
        private TB_AxisParam axisModel;
        private string id = Guid.NewGuid().ToString();
        public FrmAxisMotion()
        {
            InitializeComponent();
            GetLang(this.Controls);
            this.Text = Language.GetString("FrmAxisMotion.Name");

            this.Shown += FrmAxisMotion_Shown;
            this.FormClosing += FrmAxisMotion_FormClosing;
            Appbus.PartNo.PartNoChange += PartNo_PartNoChange;
            this.DoubleBuffered = true;
        }

        private void PartNo_PartNoChange(TB_PartNo partNo)
        {
            Init();
        }

        private void GetLang(Control.ControlCollection _controls)
        {
            foreach (Control control in _controls)
            {
                GetLang(control.Controls);
                if (control is Label)
                {
                    control.Text = Language.GetString("FrmAxisMotion." + control.Name);
                }
                else if (control is Button)
                {
                    control.Text = Language.GetString("FrmAxisMotion." + control.Name);
                }
                else if (control is DataGridView)
                {
                    DataGridView dataGridView = (DataGridView)control;
                    foreach (var item in dataGridView.Columns)
                    {
                        if (item is DataGridViewTextBoxColumn)
                        {
                            DataGridViewTextBoxColumn column = (DataGridViewTextBoxColumn)item;
                            column.HeaderText = Language.GetString("FrmAxisMotion." + column.Name);
                        }
                        else if (item is DataGridViewButtonColumn)
                        {
                            DataGridViewButtonColumn column = (DataGridViewButtonColumn)item;
                            column.HeaderText = Language.GetString("FrmAxisMotion." + column.Name);
                        }
                    }
                }
            }
        }

        private void FrmAxisMotion_FormClosing(object sender, FormClosingEventArgs e)
        {
            Appbus.PartNo.PartNoChange -= PartNo_PartNoChange;
            PubSub.Hub.Default.Unsubscribe<MonitorModel>(id);
        }

        private void FrmAxisMotion_Shown(object sender, EventArgs e)
        {
            Init();
        }
        private void Init()
        {
            this.dgv_point.Rows.Clear();
            this.IOList.Items.Clear();

            if (BcFactory.Instance.Control != null)
            {
                cmb_Directions.DataSource = BcFactory.Instance.Control.GetParam()["directionModes"];
                cmb_ZeroMode.DataSource = BcFactory.Instance.Control.GetParam()["zeroModes"];
                cmb_StopMode.DataSource = BcFactory.Instance.Control.GetParam()["stopModes"];
                cmb_pluseMode.DataSource = BcFactory.Instance.Control.GetParam()["pluseModes"];
            }

            if (Appbus.PartNo.Config != null)
                foreach (var item in Appbus.PartNo.Config.AxisPoint)
                {
                    this.dgv_point.Rows.Add(item.Name, item.ToString(), Language.GetString("FrmAxisMotion.示教"), Language.GetString("FrmAxisMotion.定位"));
                }

            if (BcFactory.Instance.Config?.IoList != null)
            {
                this.IOList.LargeImageList = this.imageList2;
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.Sensor"), 1);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.Origin"), 1);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.PositiveLimit"), 1);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.NegativeLimit"), 1);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.PositiveSoftLimit"), 1);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.NegativeSoftLimit"), 1);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.Alarm"), 1);
            }

            cob_axis.DisplayMember = "Name";
            cob_axis.ValueMember = "AxisId";
            cob_axis.DataSource = BcFactory.Instance.Config?.AxisParam;
            //cob_axis.SelectedIndex = -1;

            PubSub.Hub.Default.Subscribe<MonitorModel>(id, Monitor);
        }

        private void Monitor(MonitorModel data)
        {
            this.Invoke(new Action(() =>
            {
                AxisStatus axisStatus = data.AxisState[(ushort)cob_axis.SelectedValue];
                this.IOList.Items.Clear();
                this.IOList.LargeImageList = this.imageList2;
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.Sensor"), axisStatus.使能);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.Origin"), axisStatus.原点);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.PositiveLimit"), axisStatus.正限位);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.NegativeLimit"), axisStatus.负限位);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.PositiveSoftLimit"), axisStatus.正软限位);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.NegativeSoftLimit"), axisStatus.负软限位);
                this.IOList.Items.Add(Language.GetString("FrmAxisMotion.Alarm"), axisStatus.报警);

                txtPosition.Text = axisStatus.位置.ToString();
                txtFeedbackPos.Text = axisStatus.编码器位置.ToString();
                txtCurrentSpeed.Text = axisStatus.当前速度.ToString();
                txtSportMode.Text = axisStatus.运动模式;
                txtSportStatus.Text = axisStatus.运动状态;
                txtErrorReason.Text = axisStatus.停止原因;
                txtAxisState.Text = axisStatus.轴状态机;
                txtError.Text = axisStatus.轴错误码;
                txtBackZero.Text = axisStatus.回零结果;
            }));
        }

        public void Save()
        {
            var axis = BcFactory.Instance.Config.AxisParam.Where(p => p.AxisId == (ushort)cob_axis.SelectedValue).FirstOrDefault();
            if (axis != null)
                axisModel = axis;
            else
                axisModel = new TB_AxisParam();

            axisModel.AxisId = (ushort)cob_axis.SelectedValue;
            if (!string.IsNullOrEmpty(txt_sportSpeed.Text))
                axisModel.Max_val = Convert.ToDouble(txt_sportSpeed.Text);
            if (!string.IsNullOrEmpty(txt_manualval.Text))
                axisModel.Manual_val = Convert.ToDouble(txt_manualval.Text);
            if (!string.IsNullOrEmpty(txt_beginSpeed.Text))
                axisModel.Min_val = Convert.ToDouble(txt_beginSpeed.Text);
            if (!string.IsNullOrEmpty(txt_StopSpeed.Text))
                axisModel.Stop_val = Convert.ToDouble(txt_StopSpeed.Text);
            if (!string.IsNullOrEmpty(txt_tacc.Text))
                axisModel.Tacc = Convert.ToDouble(txt_tacc.Text);
            if (!string.IsNullOrEmpty(txt_tdec.Text))
                axisModel.Tdec = Convert.ToDouble(txt_tdec.Text);
            if (!string.IsNullOrEmpty(txt_sPara.Text))
                axisModel.S_Para = Convert.ToDouble(txt_sPara.Text);

            axisModel.Zero_dir = cmb_Directions.SelectedIndex;
            axisModel.Zero_Model = cmb_ZeroMode.SelectedIndex;
            if (!string.IsNullOrEmpty(txt_zeroVal.Text))
                axisModel.Zero_val = Convert.ToDouble(txt_zeroVal.Text);

            if (!string.IsNullOrEmpty(txt_currentVal.Text))
                axisModel.Current_val = Convert.ToDouble(txt_currentVal.Text);
            axisModel.Plus_Model = cmb_pluseMode.SelectedIndex;

            if (axis == null)
                BcFactory.Instance.Config.AxisParam.Add(axisModel);

            BcFactory.Instance.Save();

            BcFactory.Instance.Control.DownAxisParam();
        }

        public void MRefresh()
        {
            this.dgv_point.Rows.Clear();
            if (Appbus.PartNo.Config != null)
                foreach (var item in Appbus.PartNo.Config.AxisPoint)
                {
                    this.dgv_point.Rows.Add(item.Name, item.ToString(), "示教", "定位");
                }
        }

        private void cob_axis_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cob_axis.SelectedValue != null)
            {
                var axis = BcFactory.Instance.Config.AxisParam.Where(p => p.AxisId == (ushort)cob_axis.SelectedValue).FirstOrDefault();
                if (axis != null)
                {
                    cob_axis.SelectedValue = axis.AxisId;
                    txt_sportSpeed.Text = axis.Max_val.ToString();
                    txt_manualval.Text = axis.Manual_val.ToString();
                    txt_beginSpeed.Text = axis.Min_val.ToString();
                    txt_StopSpeed.Text = axis.Stop_val.ToString();
                    txt_tacc.Text = axis.Tacc.ToString();
                    txt_tdec.Text = axis.Tdec.ToString();
                    txt_sPara.Text = axis.S_Para.ToString();
                    cmb_Directions.SelectedIndex = axis.Zero_dir;
                    cmb_ZeroMode.SelectedIndex = axis.Zero_Model;
                    txt_zeroVal.Text = axis.Zero_val.ToString();
                    txt_currentVal.Text = axis.Current_val.ToString();
                    cmb_pluseMode.SelectedIndex = axis.Plus_Model;
                }
            }
        }

        private void dgv_point_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            Dialog dialog = new Dialog();
            int rowIndex = e.RowIndex;
            if (BcFactory.Instance.RunModel == StateEnum.自动模式)
            {
                dialog.Warning("自动模式下不允许操作");
                return;
            }
            if (rowIndex > -1 && e.ColumnIndex > -1)
            {
                DataGridViewRow _SelectRowPoint = this.dgv_point.SelectedRows[0];
                string pointName = _SelectRowPoint.Cells[0].Value.ToString();
                var point = Appbus.PartNo.Config.AxisPoint.Where(p => p.Name == pointName).FirstOrDefault();

                //if (dgv_point.Columns[e.ColumnIndex].HeaderText == "示教" || dgv_point.Columns[e.ColumnIndex].HeaderText == "Teach")// 示教
                if (dgv_point.Columns[e.ColumnIndex].HeaderText == "示教" || dgv_point.Columns[e.ColumnIndex].HeaderText == "Teach")// 示教
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("是否确定示教?", "确定", messButton);
                    if (dr == DialogResult.OK)
                    {
                        foreach (var item in point.AxisPointDic)
                        {
                            item.Value.Point = BcFactory.Instance.Control.GetAxisPosition(item.Value.AxisId);
                        }
                        this.dgv_point[1, rowIndex].Value = point.ToString();
                        Appbus.PartNo.Save();
                    }
                }
                else if (dgv_point.Columns[e.ColumnIndex].HeaderText == "定位" || dgv_point.Columns[e.ColumnIndex].HeaderText == "Positioning")// 定位
                {
                    if (!(bool)Cache.GetCache(CONST.BC_ISRESET))
                    {
                        dialog.Warning("请先复位");
                        Log4.Warr("请先复位");
                        return;
                    }

                    Task.Run(() =>
                    {
                        foreach (var item in point.AxisPointDic)
                        {
                            BcFactory.Instance.Control.Move_Location((ushort)item.Value.AxisId, item.Value.Point);
                        }
                    });
                }
            }
        }

        private void btn_clearAlert_Click(object sender, EventArgs e)
        {
            Save();
            Task.Run(() =>
            {
                BcFactory.Instance.Control.ClearAlart(axisModel.AxisId);
            });
        }

        private void btn_goHome_Click(object sender, EventArgs e)
        {
            Save();
            Task.Run(() =>
            {
                this.Invoke(new Action(() =>
                {
                    btn_goHome.BackColor = Color.Cyan;
                }));
                BcFactory.Instance.Control.Move_BackZero(axisModel.AxisId);
                this.Invoke(new Action(() =>
                {
                    btn_goHome.BackColor = SystemColors.Control;
                }));
            });
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            Save();
            Task.Run(() =>
            {
                BcFactory.Instance.Control.Stop(axisModel.AxisId);
            });
        }

        private void btn_jog__MouseDown(object sender, MouseEventArgs e)
        {
            Save();
            double distance = !string.IsNullOrEmpty(txt_sportDistance.Text) ? Convert.ToDouble(txt_sportDistance.Text) : 0;
            Task.Run(new Action(() =>
            {
                this.Invoke(new Action(() =>
                {
                    btn_jog_.BackColor = Color.Cyan;
                }));
                BcFactory.Instance.Control.Move(axisModel.AxisId, (ushort)MoveDir.反方向);
            }));
        }

        private void btn_jog__MouseLeave(object sender, EventArgs e)
        {

        }

        private void btn_jog_MouseDown(object sender, MouseEventArgs e)
        {
            Save();
            double distance = !string.IsNullOrEmpty(txt_sportDistance.Text) ? Convert.ToDouble(txt_sportDistance.Text) : 0;
            Task.Run(new Action(() =>
            {
                this.Invoke(new Action(() =>
                {
                    btn_jog.BackColor = Color.Cyan;
                }));
                BcFactory.Instance.Control.Move(axisModel.AxisId, (ushort)MoveDir.正方向);
            }));
        }

        private void btn_jog_MouseUp(object sender, MouseEventArgs e)
        {
            Task.Run(new Action(() =>
            {
                this.Invoke(new Action(() =>
                {
                    btn_jog.BackColor = SystemColors.Control;
                }));
                BcFactory.Instance.Control.Stop(axisModel.AxisId);
            }));
        }

        private void btn_move__Click(object sender, EventArgs e)
        {
            Save();
            double distance = !string.IsNullOrEmpty(txt_sportDistance.Text) ? Convert.ToDouble(txt_sportDistance.Text) : 0;
            Task.Run(() =>
            {
                BcFactory.Instance.Control.Move_Ration(axisModel.AxisId, (ushort)MoveDir.反方向, distance);
            });
        }

        private void btn_move_Click(object sender, EventArgs e)
        {
            Save();
            double distance = !string.IsNullOrEmpty(txt_sportDistance.Text) ? Convert.ToDouble(txt_sportDistance.Text) : 0;
            Task.Run(() =>
            {
                BcFactory.Instance.Control.Move_Ration(axisModel.AxisId, (ushort)MoveDir.正方向, distance);
            });
        }

        private void btn_sensor_Click(object sender, EventArgs e)
        {
            Save();
            Task.Run(() =>
            {
                BcFactory.Instance.Control.SetSevon(axisModel.AxisId, true);
            });
        }

        private void btn_jog__MouseUp(object sender, MouseEventArgs e)
        {
            Task.Run(new Action(() =>
            {
                this.Invoke(new Action(() =>
                {
                    btn_jog_.BackColor = SystemColors.Control;
                }));
                BcFactory.Instance.Control.Stop(axisModel.AxisId);
            }));
        }

        private void btnStopAll_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                BcFactory.Instance.Control.StopALL();
            });
        }
    }
}
